<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面标题 -->
    <div class="bg-white border-b border-gray-200 shadow-sm">
      <div class="container mx-auto px-4 py-5">
        <h1 class="text-2xl font-bold text-gray-800">AI文章生成</h1>
        <p class="text-gray-500 mt-1">通过AI快速生成高质量原创文章内容</p>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="container mx-auto px-4 py-6">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧：参数设置 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-lg shadow-sm p-5 sticky top-4">
            <h2 class="text-lg font-medium text-gray-800 mb-4">生成参数</h2>
            
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">文章标题</label>
                <input
                  type="text"
                  v-model="form.title"
                  class="form-input w-full"
                  placeholder="输入文章标题或主题"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">关键词</label>
                <input
                  type="text"
                  v-model="form.keywords"
                  class="form-input w-full"
                  placeholder="输入核心关键词，用逗号分隔"
                >
                <p class="text-xs text-gray-500 mt-1">例如：人工智能, 未来趋势, 技术应用</p>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">文章长度</label>
                <select
                  v-model="form.length"
                  class="form-input w-full"
                >
                  <option value="short">短篇 (300-500字)</option>
                  <option value="medium" selected>中篇 (800-1200字)</option>
                  <option value="long">长篇 (1500-2000字)</option>
                  <option value="extra_long">超长 (2000字以上)</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">写作风格</label>
                <select
                  v-model="form.style"
                  class="form-input w-full"
                >
                  <option value="formal">正式严谨</option>
                  <option value="casual">轻松随意</option>
                  <option value="professional" selected>专业权威</option>
                  <option value="creative">创意十足</option>
                  <option value="persuasive">说服性强</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">目标受众</label>
                <select
                  v-model="form.audience"
                  class="form-input w-full"
                >
                  <option value="general">普通大众</option>
                  <option value="professionals">专业人士</option>
                  <option value="students">学生群体</option>
                  <option value="business">商业人士</option>
                  <option value="tech">科技爱好者</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">额外要求</label>
                <textarea
                  v-model="form.requirements"
                  class="form-input w-full min-h-[100px]"
                  placeholder="输入其他特殊要求或说明..."
                ></textarea>
              </div>
              
              <div class="pt-2">
                <button
                  class="btn btn-primary w-full flex items-center justify-center"
                  :disabled="loading || !form.title"
                  @click="generateArticle"
                >
                  <i v-if="loading" class="fa fa-spinner fa-spin mr-2"></i>
                  <span>生成文章</span>
                </button>
                <button
                  class="btn btn-secondary w-full mt-3"
                  @click="clearForm"
                >
                  重置参数
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 右侧：生成结果 -->
        <div class="lg:col-span-2">
          <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <!-- 结果工具栏 -->
            <div class="bg-gray-50 px-5 py-3 border-b border-gray-200 flex flex-wrap items-center justify-between gap-3">
              <h2 class="text-lg font-medium text-gray-800">生成结果</h2>
              
              <div class="flex gap-2">
                <button
                  class="btn btn-secondary flex items-center"
                  :disabled="!articleContent"
                  @click="copyToClipboard"
                >
                  <i class="fa fa-copy mr-1"></i>复制
                </button>
                <button
                  class="btn btn-secondary flex items-center"
                  :disabled="!articleContent"
                  @click="downloadArticle"
                >
                  <i class="fa fa-download mr-1"></i>下载
                </button>
                <button
                  class="btn btn-primary flex items-center"
                  :disabled="!articleContent || loading"
                  @click="regenerateArticle"
                >
                  <i v-if="loading" class="fa fa-spinner fa-spin mr-1"></i>
                  <i v-else class="fa fa-refresh mr-1"></i>
                  重新生成
                </button>
              </div>
            </div>
            
            <!-- 结果内容区 -->
            <div class="p-5">
              <!-- 空状态 -->
              <div v-if="!articleContent && !loading" class="py-16 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-file-text-o text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">尚未生成文章</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  设置左侧参数并点击"生成文章"按钮，AI将为您创建高质量内容
                </p>
              </div>
              
              <!-- 加载状态 -->
              <div v-if="loading" class="py-16 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-spinner fa-spin text-2xl text-primary"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">AI正在生成文章</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  请稍候，AI正在根据您的需求创作内容...
                </p>
              </div>
              
              <!-- 生成结果 -->
              <div v-if="articleContent && !loading" class="prose max-w-none">
                <h1 class="text-2xl font-bold text-gray-800 mb-4">{{ articleTitle }}</h1>
                
                <div class="flex items-center text-sm text-gray-500 mb-6">
                  <span><i class="fa fa-clock-o mr-1"></i> 生成时间: {{ generateTime }}</span>
                  <span class="mx-3">|</span>
                  <span><i class="fa fa-file-text-o mr-1"></i> 约 {{ wordCount }} 字</span>
                </div>
                
                <div v-html="formattedArticleContent" class="text-gray-700 leading-relaxed"></div>
              </div>
            </div>
          </div>
          
          <!-- 历史记录 -->
          <div class="bg-white rounded-lg shadow-sm mt-6">
            <div class="px-5 py-3 border-b border-gray-200">
              <h2 class="text-lg font-medium text-gray-800">生成历史</h2>
            </div>
            <div class="p-0">
              <div 
                v-for="(history, index) in generateHistory" 
                :key="index"
                class="px-5 py-3 border-b border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors"
                @click="loadHistory(history)"
              >
                <div class="font-medium text-gray-800 truncate">{{ history.title }}</div>
                <div class="flex items-center justify-between mt-1">
                  <span class="text-xs text-gray-500">{{ formatHistoryTime(history.timestamp) }}</span>
                  <span class="text-xs text-gray-500">{{ history.wordCount }} 字</span>
                </div>
              </div>
              
              <div v-if="generateHistory.length === 0" class="px-5 py-8 text-center text-gray-500 text-sm">
                暂无生成历史
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { formatDate } from '@/utils/date'

// 表单数据
const form = ref({
  title: '',
  keywords: '',
  length: 'medium',
  style: 'professional',
  audience: 'general',
  requirements: ''
})

// 生成状态
const loading = ref(false)
const articleContent = ref('')
const articleTitle = ref('')
const generateTime = ref('')
const wordCount = ref(0)
const formattedArticleContent = ref('')
const generateHistory = ref([])

// 生成文章
const generateArticle = async () => {
  if (!form.value.title) return
  
  loading.value = true
  try {
    // 模拟AI生成过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 根据参数生成不同长度的内容
    let content = ''
    const paragraphs = []
    
    // 生成段落数量根据长度设置
    const paragraphCount = form.value.length === 'short' ? 2 
      : form.value.length === 'medium' ? 4 
      : form.value.length === 'long' ? 6 
      : 8
    
    // 生成段落内容
    for (let i = 0; i < paragraphCount; i++) {
      let para = ''
      // 每段句子数量
      const sentenceCount = Math.floor(Math.random() * 3) + 3
      
      for (let j = 0; j < sentenceCount; j++) {
        // 随机句子长度
        const wordLength = Math.floor(Math.random() * 10) + 10
        para += generateRandomSentence(wordLength, form.value.title, form.value.keywords) + ' '
      }
      
      paragraphs.push(para.trim())
    }
    
    // 格式化内容为HTML
    content = paragraphs.map(p => `<p>${p}</p>`).join('\n\n')
    
    // 添加小标题
    if (paragraphCount > 3) {
      content = content.replace('</p>', '</p>\n\n<h3>深入分析</h3>')
    }
    
    // 更新结果
    articleTitle.value = form.value.title
    articleContent.value = content
    formattedArticleContent.value = content
    generateTime.value = new Date().toLocaleString()
    wordCount.value = content.replace(/<[^>]*>/g, '').length
    
    // 保存到历史记录
    saveToHistory()
    
  } catch (error) {
    console.error('生成文章失败:', error)
  } finally {
    loading.value = false
  }
}

// 重新生成文章
const regenerateArticle = () => {
  generateArticle()
}

// 保存到历史记录
const saveToHistory = () => {
  const historyItem = {
    title: articleTitle.value,
    content: articleContent.value,
    timestamp: new Date().getTime(),
    wordCount: wordCount.value,
    params: { ...form.value }
  }
  
  generateHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (generateHistory.value.length > 10) {
    generateHistory.value.pop()
  }
}

// 加载历史记录
const loadHistory = (history) => {
  articleTitle.value = history.title
  articleContent.value = history.content
  formattedArticleContent.value = history.content
  generateTime.value = new Date(history.timestamp).toLocaleString()
  wordCount.value = history.wordCount
  form.value = { ...history.params }
}

// 格式化历史时间
const formatHistoryTime = (timestamp) => {
  return formatDate(new Date(timestamp), 'yyyy-MM-dd HH:mm')
}

// 复制到剪贴板
const copyToClipboard = () => {
  if (!articleContent.value) return
  
  // 提取纯文本内容
  const textContent = articleContent.value.replace(/<[^>]*>/g, '')
  navigator.clipboard.writeText(textContent)
    .then(() => {
      alert('内容已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
    })
}

// 下载文章
const downloadArticle = () => {
  if (!articleContent.value) return
  
  // 提取纯文本内容
  const textContent = articleTitle.value + '\n\n' + 
                     articleContent.value.replace(/<[^>]*>/g, '\n\n')
  
  const blob = new Blob([textContent], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${articleTitle.value.replace(/\s+/g, '_')}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 清空表单
const clearForm = () => {
  form.value = {
    title: '',
    keywords: '',
    length: 'medium',
    style: 'professional',
    audience: 'general',
    requirements: ''
  }
}

// 生成随机句子（模拟AI生成）
const generateRandomSentence = (length, title, keywords) => {
  const words = [
    '人工智能', '技术', '发展', '应用', '未来', '趋势', '数据', '分析', 
    '创新', '解决方案', '挑战', '机遇', '研究', '发现', '重要', '关键',
    '影响', '改变', '提升', '优化', '效率', '安全', '智能', '自动化',
    '学习', '适应', '进化', '突破', '革命', '转型'
  ]
  
  // 添加关键词到可用词汇
  if (keywords) {
    keywords.split(',').forEach(keyword => {
      const kw = keyword.trim()
      if (kw && !words.includes(kw)) {
        words.push(kw)
      }
    })
  }
  
  // 添加标题词汇
  if (title) {
    title.split(/\s+/).forEach(word => {
      if (word && !words.includes(word)) {
        words.push(word)
      }
    })
  }
  
  // 随机生成句子
  let sentence = ''
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * words.length)
    sentence += words[randomIndex] + (i < length - 1 ? ' ' : '')
  }
  
  // 首字母大写并添加标点
  return sentence.charAt(0) + sentence.slice(1) + (Math.random() > 0.8 ? '。' : '，')
}
</script>
